const { ipcMain, screen ,BrowserWindow} = require('electron');
const path = require('path')
const url = require('url');
const log = require('electron-log');

const { OPEN_CHAT_WINDOW, CLOSE_CHAT_WINDOW, END_CHAT_WINDOW, CHAT_WINDOW_CLOSE_REPLY,SEND_DATA_TO_WINDOW,SDK_APP_ID } = require("./const/const");


const getSrceenSize = () => {
    const display = screen.getPrimaryDisplay();
    return display.size;
}

class ChatWindowIpc {
    chatWindow = null;
    readyToChatShowWindow = false;

    constructor() {
        this.mount();
    }

    mount() {
        this.createWindow();
        this.addEventListiner();
    }

    destroy() {
        this.offEventListiner();
        this.addEventListiner();
    }

    createWindow() {
        this.chatWindow = null;
        const { NODE_ENV, HUARUN_ENV } = process.env;
        const isDev = NODE_ENV?.trim() === 'development';
        const chatWindow = new BrowserWindow({
            height:640,
            width: 960,
            minWidth: 850,
            minHeight: 600,
            show: false,
            frame: false,
            webPreferences: {
                parent: this.win,
                webSecurity: true,
                nodeIntegration: true,
                nodeIntegrationInWorker: true,
                enableRemoteModule: true,
                contextIsolation: false,
            },
        });
        chatWindow.removeMenu();
        if (isDev) {
			// chatWindow.webContents.openDevTools(); //正式生产不需要开启
            chatWindow.loadURL(`http://localhost:3000/chat.html`);
        } else {
            //callWindow.webContents.openDevTools(); //正式生产不需要开启
            chatWindow.loadURL(
                url.format({
                    pathname: path.join(__dirname, `../../bundle/chat.html`),
                    protocol: 'file:',
                    slashes: true
                })
            );
        }

        chatWindow.on('ready-to-show', () => {
            this.readyToChatShowWindow = true;  
        });

        this.readyToChatShowWindow = false;

        this.chatWindow = chatWindow;
    }

    addEventListiner() {
        const { NODE_ENV } = process.env;
        const isDev = NODE_ENV?.trim() === 'development';
        const screenSize = getSrceenSize();
        
       

        ipcMain.on(CLOSE_CHAT_WINDOW, () => {
			this.chatWindow.close()
        });

        ipcMain.on(END_CHAT_WINDOW, () => {
            this.chatWindow.close()
        })
		
		ipcMain.on(SEND_DATA_TO_WINDOW, (event,data) => {
		   if(this.readyToChatShowWindow) {
				this.chatWindow.webContents.send('pass-chat-data', JSON.stringify(data));
		   }
		})
       
	   
        ipcMain.on(OPEN_CHAT_WINDOW, (event,data) => {            
            if(data.windowType === 'chatWindow'){
            	this.chatWindow.setMinimumSize(400, 650);
            	// this.chatWindow.setSize(1000, 650);
            	this.chatWindow.setPosition(Math.floor((screenSize.width - 400) / 2), Math.floor((screenSize.height - 650) / 2));
            	
            				
            }

            const showWindow = (timer) => {
                this.chatWindow.show();	
				this.chatWindow.webContents.send('pass-chat-data', JSON.stringify(data));
                isDev && this.chatWindow.webContents.openDevTools();
                timer && clearInterval(timer);
								
            }

            if(this.readyToChatShowWindow) {
                showWindow();
            } else {
                const timer = setInterval(() => {
                    if(this.readyToChatShowWindow) {
                        showWindow(timer);
                    }
                }, 10);

            }
        });

        this.chatWindow.on('close', () => {
            try {
                this.createWindow()
            } catch(err) {
                console.log(err);
            }
        });

        this.chatWindow.on('closed', () => {
            try {
                this.destroy();
            } catch (err) {
                console.log(err);
            }
        });
    }

    offEventListiner() {
        ipcMain.removeAllListeners(OPEN_CHAT_WINDOW);
		ipcMain.removeAllListeners(SEND_DATA_TO_WINDOW);
     
		
        // 当接受方拒绝通话后，调用该方法可关闭窗口，并退出房间
        ipcMain.removeAllListeners(CLOSE_CHAT_WINDOW);

        ipcMain.removeAllListeners(END_CHAT_WINDOW)
       
    }
};

module.exports = ChatWindowIpc;